package com.jozen.modelbase.netwoek.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Handler;

import androidx.multidex.MultiDex;

import com.google.gson.Gson;
import com.jozen.modelbase.netwoek.util.SpMkvUtils;
import com.tencent.mmkv.MMKV;

import java.util.HashSet;
import java.util.Set;


public abstract class ModuleBaseApplication extends Application {
    private static ModuleBaseApplication INSTANCE = null;
    private static Context context;
    //主线程handler
    private static Handler mHandler;
    private static Gson gson = new Gson();
    private Set<Activity> allActivities;


    public static Gson getGson() {
        return gson;
    }

    public static ModuleBaseApplication getInstance() {
        return INSTANCE;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        INSTANCE = this;
        context = getApplicationContext();
        mHandler = new Handler();
        initMkv();
        initSmartToilet();
    }


    //提高 IO效率替代SharedPreferences
    private void initMkv() {
        String dir = getFilesDir().getAbsolutePath() + "/mmkv";
        String rootDir = MMKV.initialize(dir);
        SpMkvUtils.getInstance();
    }

    public abstract void initSmartToilet();

    public static Handler getHandler() {
        return mHandler;
    }

    public static Context getContext() {
        return context;
    }

    /**
     * 添加activity
     *
     * @param act
     */
    public void addActivity(Activity act) {
        if (allActivities == null) {
            allActivities = new HashSet<>();
        }
        allActivities.add(act);
    }

    public Set<Activity> getActivityList(){
        return allActivities;
    }



    /**
     * 移除activity
     *
     * @param act
     */
    public void removeActivity(Activity act) {
        if (allActivities != null) {
            allActivities.remove(act);
        }
    }

    public void finishActivity() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
    }

    /**
     * 退出程序
     */
    public void exitApp() {
        if (allActivities != null) {
            synchronized (allActivities) {
                for (Activity act : allActivities) {
                    act.finish();
                }
            }
        }
        finishApplication();
    }

    /**
     * 结束进程
     */
    public void finishApplication() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }



    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

